package com.cman777.springc.springali.trace;

import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.slf4j.MDC;
import org.springframework.util.StringUtils;

/**
 * @author chenzhicong
 * @time 2020/12/8 17:36
 */
@Activate(group = {CommonConstants.PROVIDER, CommonConstants.CONSUMER}, order = -999)
public class RpcTraceFilter implements Filter {
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        String traceId = RpcContext.getContext().
                getAttachment("traceId");
        if (StringUtils.isEmpty(traceId)) {
            //如果没有代表是上游服务,则从MDC变量取出来然后放进RPC上下文
            String tid = MDC.get("requestId");
            if (!StringUtils.isEmpty(tid)) {
                RpcContext.getContext().setAttachment("traceId", tid);
            }
        } else {
            //如果有则代表是下游服务
            String tid = MDC.get("requestId");
            if (StringUtils.isEmpty(tid)) {
                MDC.put("requestId", tid);
            }
        }
        return invoker.invoke(invocation);
    }
}
